package bible.sunflower.work.yinfeng.socket;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerApp {

	public static void main(String args[]){ 
		try{ 
			boolean flag=true; 
			Socket clientSocket=null; 
			int c; 
		
			ServerSocket sSocket=new ServerSocket(1888); 
			System.out.println("Server listen on:"+sSocket.getLocalPort()); 
		
			while(flag) { 
				clientSocket=sSocket.accept(); 
				BufferedInputStream bis =  new BufferedInputStream(clientSocket.getInputStream()); 
				OutputStream os=clientSocket.getOutputStream();
				
				byte[] contentLength = new byte[8];			
				bis.read( contentLength );
				Integer cLength = Integer.parseInt( new String( contentLength ) );
				System.out.println( "receive msg length is " + cLength );
								
				StringBuffer sb = new StringBuffer();
				/*
				byte[] byteArray = new byte[512];
				int byteRead = 0;
				int readLength = 0;
				while( (byteRead = bis.read( byteArray )) > 0 ){ 
					
				    sb.append( new String(byteArray, 0, byteRead) );
				    System.out.println("sb is " + new String(byteArray, 0, byteRead) );				    
				    readLength += byteRead;
				    System.out.println("byte read is " + byteRead + ", readLength is " + readLength );
				    if( readLength >= cLength ){
				    	break;
				    }
				}
				*/
				
				
				byte[] byteBuffer = new byte[ cLength ];
				bis.read( byteBuffer );
				sb.append( new String( byteBuffer ) );
				
				System.out.println("client message is: " + sb.toString() ); 
				os.write("00000018code:200,status:ok".getBytes());
				os.flush();
				System.out.println("--END--");
				bis.close(); 
				os.close(); 
				clientSocket.close(); 
			} 
			    sSocket.close(); 
			} 
		catch(Exception e){ 
			e.printStackTrace();
		    System.err.println("server Exception :"+ e.getMessage()); 
		} 
	} 

}
